package cn.gqr.dao;

import cn.gqr.entity.Blog;
import cn.gqr.entity.Collect;
import cn.gqr.uitl.SessionUitl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class CollectDao {

    @Autowired
    MongoTemplate mT;

    @Autowired
    BolgsDao bd;


    //添加收藏  参数博客 id
    public Collect addCollect(String bid){
        return mT.insert(new Collect( SessionUitl.user().getId(),bid));
    }

    //查看文章是否收藏
    public boolean checkCollect(Collect collect){
        Query q = new Query();
        q.addCriteria(Criteria.where("uid").is(SessionUitl.user().getId()).and("bid").is(collect.getBid()));
        Collect co = mT.findOne(q, Collect.class);
        return co!=null?true:false;
    }

    //根据id取消收藏
    public boolean cancelCollect(String bid){
        Criteria c = new Criteria().where("bid").is(bid).and("uid").is(SessionUitl.user().getId());
        return mT.remove(new Query(c),Collect.class).wasAcknowledged();
    }

    //根据博客id减少收藏数量
    public boolean CollectNum(Blog blog,boolean b){
        Query q = new Query();
        q.addCriteria(Criteria.where("id").is(blog.getId()));
        int num = b?blog.getCollectNum()+1:blog.getCollectNum()-1;
        Update u = new Update().set("collect_num", num);
        return mT.updateFirst(q,u,Blog.class).wasAcknowledged();
    }

    //获取登录用户的所有收藏信息
    public List<Collect> findByPage(int start){
        Pageable of = PageRequest.of(start<0?0:start, 3);
        Query q = new Query().with(of);
        q.addCriteria(Criteria.where("uid").is(SessionUitl.user().getId()));
        List<Collect> collects = mT.find(q, Collect.class);
        return collects;
    }

    //获取根据id查找收藏的数据行数
    public long collectCount(){
        Query q = new Query();
        Criteria c = Criteria.where("uid").is(SessionUitl.user().getId());
        q.addCriteria(c);
        return mT.count(q, Collect.class);
    }


}
